<?php

class UserService {

    /**
     * '体检报告'->'健康指导'
     * 1. 将'原始体检报告'里面的文字性解释拿出来
     * 2. 不正常指标，从我们自己的exam_item/ indicator里面拼接出来
     * TODO 把每个不正常的体检项目，通过exam item表解读出来
     * @param array $arr
     */
    public function reportana($arr) {
        $reportGuide = new EvaluateReportGuide();
        $guide = $reportGuide->findByAttributes(array("uid" => $arr['uid']));

        $ret = "";
        if ($guide !== null) {
            $ret = str_replace(array("\r\n", "\n", "\r"), '<br />', $guide['guidence']);
        }

        return $ret;
    }

    /**
     * app修改个人信息接口(新)
     * @param $POST["uid"] uid
     * @param $POST["realname"] 姓名
     * @param $POST["oldpass"] 旧密码
     * @param $POST["newpass"] 新密码
     * @param $POST["idcard"] 身份证号
     */
    public function modifyInfo($arr) {
        if (!isset($arr["uid"])) {
            return JSONHelper::ERROR_ILLEGAL_REQUEST;
        }

        $uid = trim($arr["uid"]);
        $user = B2bUser::model()->findByPk($uid);
        if (!$user) {
            return JSONHelper::ERROR_USER_EXISTS;
        }

//        $oldpass = $arr["oldpass"];
//        if ($user->password !== $oldpass) {
//            return JSONHelper::ILLEGAL_LOGIN;
//        }
//
//        if (isset($arr["newpass"])) {
//            $newpass = trim($arr["newpass"]);
//            $user->password = $newpass;
//        }

        if (isset($arr["realname"])) {
            $realname = trim($arr["realname"]);
            $user->realname = $realname;
        }
        if (isset($arr["idcard"])) {
            //3 身份证号码检测
            $id_card = trim($arr["idcard"]);
            if (!preg_match('/^(\d{18,18}|\d{15,15}|\d{17,17}x)$/', $id_card)) {
                return JSONHelper::ILLEGAL_IDENTITY_NO;
            }

            $user->identity_no = $id_card;
        }

        $ret = $user->save(false);
        if ($ret === false) {
            return JSONHelper::ERROR_SERVICE;
        }

        if (isset($arr["realname"]) && isset($arr["idcard"])) {
            $realname = trim($arr["realname"]);
            $id_card = trim($arr["idcard"]);

            $tickets = B2bTicket::model()->findAllByAttributes(array("identity_no" => $id_card,
                "realname" => $realname,
                "uid" => 0));

            foreach ($tickets as $ticket) {
                $ticket->uid = $user->id;
//                $ticket->telephone = $user->telephone;
                $ticket->save();
            }
        }


        return $this->getUserInfor($user);
    }
    /**
     * app修改个人信息接口(新)
     * @param $POST["uid"] uid
     * @param $POST["realname"] 姓名
     * @param $POST["oldpass"] 旧密码
     * @param $POST["newpass"] 新密码
     * @param $POST["idcard"] 身份证号
     */
    public function modifyPwd($arr) {
        if (!isset($arr["uid"])||!isset($arr["oldpass"])||!isset($arr["newpass"])) {
            return JSONHelper::ERROR_ILLEGAL_REQUEST;
        }

        $uid = trim($arr["uid"]);
        $user = B2bUser::model()->findByPk($uid);
        if (!$user) {
            return JSONHelper::ERROR_USER_EXISTS;
        }

        $oldpass = $arr["oldpass"];
        if ($user->password !== $oldpass) {
            return JSONHelper::ILLEGAL_LOGIN;
        }
//
        if (isset($arr["newpass"])) {
            $newpass = trim($arr["newpass"]);
            $user->password = $newpass;
        }

        $ret = $user->save(false);
        if ($ret === false) {
            return JSONHelper::ERROR_SERVICE;
        }

        return true;
    }

    /**
     * app注册接口(新)
     * @param $POST["username"] 当前就是手机号
     * @param $POST["password"] 密码
     * @param $POST["realname"] 姓名
     * @param $POST["idcard"] 身份证号
     */
    public function signup($arr) {
        if (!isset($arr["username"]) || !isset($arr["password"]) || !isset($arr["captcha"])) {
            return JSONHelper::ERROR_ILLEGAL_REQUEST;
        }

        // 1 手机号检测
        $telephone = trim($arr["username"]);
        $captcha = trim($arr["captcha"]);
        if (!preg_match("/1[3-8]\d{9}$/", $telephone)) {
            return JSONHelper::ILLEGAL_TELEPHONE;
        }
        
        if(false === $this->verifySmsCaptcha($telephone, $captcha)){
            return JSONHelper::ERROR_SMS_VERIFY;
        }

        // 2 手机号是否重复
        $B2bUser = new B2bUser();
        $telephoneRepeat = $B2bUser->checkPhoneRepeat($telephone);
        if (!$telephoneRepeat) {
            return JSONHelper::REPEAT_TELEPHONE;
        }


        //保存用户
        $newUser = new B2bUser();
        $newUser->username = $telephone;
        $newUser->telephone = $telephone;
        $newUser->password = trim($arr["password"]);
        if (isset($arr["realname"])) {
            $realname = trim($arr["realname"]);
            $newUser->realname = $realname;
        }
        if (isset($arr["idcard"])) {
            //3 身份证号码检测
            $id_card = trim($arr["idcard"]);
            if (!preg_match('/^(\d{18,18}|\d{15,15}|\d{17,17}x)$/', $id_card)) {
                return JSONHelper::ILLEGAL_IDENTITY_NO;
            }

            //4 检测身份证号是否重复
            $identity_repeat = B2bUser::model()->findByAttributes(array("identity_no" => $id_card));
            if ($identity_repeat !== null) {
                return JSONHelper::REPEAT_IDENTITY;
            }

            $newUser->identity_no = $id_card;
        }

        $ret = $newUser->save(false);
        if ($ret === false) {
            return JSONHelper::ERROR_SERVICE;
        }

        if (isset($arr["realname"]) && isset($arr["idcard"])) {
            $realname = trim($arr["realname"]);
            $id_card = trim($arr["idcard"]);

            $tickets = B2bTicket::model()->findAllByAttributes(array("identity_no" => $id_card,
                "realname" => $realname,
                "uid" => 0));

            foreach ($tickets as $ticket) {
                $ticket->uid = $newUser->id;
//                $ticket->telephone = $newUser->telephone;
                $ticket->save();
            }
        }


        return $this->getUserInfor($newUser);
    }

    /**
     * app 端注册接口
     * @param $arr["user"]["idcard"]:身份证
     * @param $arr["user"]["name"]:姓名
     * @param $arr["user"]["email"]:邮箱
     * @param $arr["user"]["telephone"]:手机
     * @param $arr["user"]["password"]:密码
     * @return getUserInfor($ret, $retLogin)
     */
    public function register($arr) {
        //1、检测是否POST表单$POST["user"],否则返回错误，无效的请求
        if (!isset($arr["user"])) {
            return JSONHelper::ERROR_ILLEGAL_REQUEST;
        }
        $user = $arr["user"];

        /** 检测手机号码,失败返回错误* */
        $telephone = trim($user["telephone"]);

        //检测手机号格式是否合法
        if (!preg_match("/1[3-8]\d{9}$/", $telephone)) {
            return JSONHelper::ILLEGAL_TELEPHONE;
        }

        //检查身份证号码
        $id_card = trim($user["idcard"]);
        if (!preg_match('/^(\d{18,18}|\d{15,15}|\d{17,17}x)$/', $id_card)) {
            return JSONHelper::ILLEGAL_IDENTITY_NO;
        }

        //检测email是否合法
        $email = trim($user["email"]);
        if (!preg_match("/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/", $email)) {
            return JSONHelper::ILLEGAL_EMAIL;
        }

        //检测手机号是否重复
        $B2bUser = new B2bUser();
        $telephoneRepeat = $B2bUser->checkPhoneRepeat($telephone);
        if (!$telephoneRepeat) {
            return JSONHelper::REPEAT_TELEPHONE;
        }

        //检测email是否重复
        $mailRepeat = $B2bUser->checkEmailRepeat($email);
        if (!$mailRepeat) {
            //            echo JSONHelper::retInfo(false, JSONHelper::REPEAT_EMAIL);
            //            Yii::app()->end();
            return JSONHelper::REPEAT_EMAIL;
        }
        //检测身份证号是否重复
        $identity_repeat = B2bUser::model()->findByAttributes(array("identity_no" => $id_card));
        if ($identity_repeat !== null) {
            return JSONHelper::REPEAT_IDENTITY;
        }

        //保存用户
        $newUser = new B2bUser();
        $newUser->username = $telephone;
        $newUser->realname = trim($user["name"]);
        $newUser->telephone = $telephone;
        $newUser->identity_no = $id_card;
        $newUser->password = trim($user["password"]);
        $newUser->email = $email;
        $ret = $newUser->save(false);
        if ($ret === false) {
            return JSONHelper::ERROR_SERVICE;
        }

        return $this->getUserInfor($newUser);
    }
    public function pwdReset($arr)
    {
        if(!isset($arr["captcha"])||!isset($arr["username"])||!isset($arr["password"])){
            return JSONHelper::ERROR_ILLEGAL_REQUEST;
        }
        if(false === $this->verifySmsCaptcha($arr["username"], $arr["captcha"])){
            return JSONHelper::ERROR_SMS_VERIFY;
        }
        $user = B2bUser::model()->findByAttributes(array('username'=>$arr["username"]));
        if($user === null){
            return JSONHelper::ERROR_USER_EXISTS;
        }
        $user->password = trim($arr["password"]);
        try{
            if($user->update()===false){
                throw new Exception("重置密码错误");
            }
        } catch (Exception $ex) {
            return JSONHelper::ERROR_SERVICE;
        }
        return true;
    }

    /*
     * 登录接口
     * @param $user[username]: 手机号
     * @param user[password]：密码
     * @return return $this->getUserInfor($ret, $retLogin);
     */

    public function verify($user, $coding = true) {
        //1、检测是否POST表单$POST["user"],否则返回错误，无效的请求
        if (!isset($user["username"]) || !isset($user["password"])) {
            return JSONHelper::ERROR_ILLEGAL_REQUEST;
        }


        $login = new B2bUser();
        $username = trim($user["username"]);
        if ($coding) {
            $password = trim($user["password"]);
        } else {
            $password = md5(trim($user["password"]));
        }
        $retLogin = $login->verify($username, $password);
        if ($retLogin === false) {
            return JSONHelper::ILLEGAL_LOGIN;
        }
        $info = $this->getUserInfor($retLogin);
        return $info;
    }

    /**
     * 获取用户预约的套餐信息及体检中心
     * $_POST["uid"] 用户uid
     * @return array
     */
    public function getPackageAndCenter($arr) {
        if (!isset($arr["uid"])) {
            //错误，没有获取到用户id
            return JSONHelper::ERROR_ILLEGAL_REQUEST;
        }
        $uid = trim($arr["uid"]);

        //获取用户信息
        $user = B2bUser::model()->findByPk($uid);
        if ($user === null) {
            //错误，不存在的用户
            return JSONHelper::ERROR_USER_EXISTS;
        }

        //返回所有可预约的
        //所有新导入的可用体检（表示企业用户将数据导入到我们平台，但是还未和用户id关联)
//        if (!empty($user->identity_no) && !empty($user->realname)) {
//            $ret = B2bTicket::model()->relationUserByCardNoName($user->id, $user->identity_no, $user->realname);
//            if ($ret === false) {
//                return JSONHelper::ERROR_SERVICE;
//            }
//        }
        //查找所有该用户关联的体检tickets
        
        $tickets = B2bTicket::model()->findAllByAttributes(array(
            "uid" => $user->id,
            "tstatus"=>array( B2bTicket::UNACTIVATED,
                B2bTicket::YUYUE_PROCESSING,
                B2bTicket::YUYUE_CONFIRM,
                B2bTicket::YUYUE_REFUSED
            )), array("order" => "`tstatus`=".B2bTicket::UNACTIVATED.",
                `tstatus`=".B2bTicket::YUYUE_CONFIRM.",
                `tstatus`=".B2bTicket::YUYUE_PROCESSING.",`tstatus`=".B2bTicket::YUYUE_REFUSED));

        $items = array();

        foreach ($tickets as $it) {
            //未关联任何套餐的ticket直接忽略掉
            $package = $it->package;
//            if($package === null){
//                continue;
//            }
            $item["tid"] = $it->id;
            $item["activecode"] = $it->activecode;
            $item["status"] = $it->tstatus;
            if (intval($it->companyid) != 0) {
                $item["realname"] = $it->realname;
                $item["identity_no"] = $it->identity_no;
                $item["type"] = B2bTicket::COMPANYUSER;
            } else {
                $item["type"] = B2bTicket::GENERALUSER;
            }

            if ($it->tstatus != B2bTicket::UNACTIVATED) {
                if($it->center === null || $package === null){
                    return JSONHelper::ERROR_TICKET_INFO;
                }
                $item["realname"] = $it->realname;
                $item["telephone"] = $it->telephone;
                $item["identity_no"] = $it->identity_no;
                $item["packagename"] = $package->name;
                $item["packageimg"] = $package->small_img;
                $item["packagebigimg"] = $package->big_img;
                $item["packagedesc"] = $package->description;
                $c["id"] = $it->center->id;
                $c["name"] = $it->center->name;
                $c["date"] = $it->examdate;
                $item["centers"] = $c;
            }elseif($package !== null){
                $item["packagename"] = $package->name;
                $item["packageimg"] = $package->small_img;
                $item["packagedesc"] = $package->description;
                $item["packagecenternum"] = B2bPackageToCenter::model()->count("package_id='{$package->id}'");
            }else{
                $item["packagename"] = "您有多个可选套餐";
                $item["packageimg"] = Yii::app()->baseUrl."/upload/package/default_s.png";

                $item["packagedesc"] = "请在预约界面先选择套餐";
                $item["packagecenternum"] = 0;
            }
            array_push($items, $item);
        }
        return $items;
    }

    /**
     * 获取某次tickets详情
     */
    public function getTicketDetails($arr) {
        if (!isset($arr["uid"]) || !isset($arr['tid'])) {
            return JSONHelper::ERROR_ILLEGAL_REQUEST;
        }
        $ticket = B2bTicket::model()->findByAttributes(array(
            "id" => $arr['tid'], "uid" => $arr["uid"]
        ));
        if (null === $ticket) {
            return JSONHelper::ERROR_ILLEGAL_TICKET;
        }
        if ($ticket->package === null || $ticket->package->centers === array()) {
            return JSONHelper::ERROR_SERVICE;
        }
        $item = array();
        $item["id"] = $ticket->id;
        $item["packagename"] = $ticket->package->name;
//        $item["packageimg"] = $ticket->package->big_img;
        $item["status"] = $ticket->tstatus;

        if (intval($ticket->companyid) != 0) {
            if ($ticket->identity_no == null || $ticket->realname == null) {
                return JSONHelper::ERROR_TICKET_COMPANY;
            }
            $item["identity_no"] = $ticket->identity_no;
            $item["realname"] = $ticket->realname;
            $item["startdate"] = $ticket->startdate;
            $item["enddate"] = $ticket->enddate;
            $item["type"] = B2bTicket::COMPANYUSER;
        } else {
            $item["type"] = B2bTicket::GENERALUSER;
        }
        $item["centers"] = array();
        if ($ticket->tstatus != B2bTicket::UNACTIVATED) {
            if (null === $ticket->center) {
                return JSONHelper::ERROR_SERVICE;
            }
            $c["id"] = $ticket->center->id;
            $c["name"] = $ticket->center->name;
            $c["address"] = $ticket->center->address;
            $c["province"] = $ticket->center->province;
            $c["city"] = $ticket->center->city;
            //$c["telephone"] = $ticket->center->telephone;
            $c["gps_lat"] = $ticket->center->gps_lat;
            $c["gps_lon"] = $ticket->center->gps_lon;
            $item["realname"] = $ticket->realname;
            $item["telephone"] = $ticket->telephone;
            $item["identity_no"] = $ticket->identity_no;
            $item["examdate"] = $ticket->examdate;
            array_push($item["centers"], $c);
        } else {
            foreach ($ticket->package->centers as $center) {
                $c["id"] = $center->center->id;
                $c["name"] = $center->center->name;
                $c["address"] = $center->center->address;
                $c["province"] = $center->center->province;
                $c["city"] = $center->center->city;
                //$c["telephone"] = $center->center->telephone;
                $c["gps_lat"] = $center->center->gps_lat;
                $c["gps_lon"] = $center->center->gps_lon;
                array_push($item["centers"], $c);
            }
        }
        return $item;
    }

    //获取用户接口信息
    // return array
    private function getUserInfor($user) {
        if ($user instanceof B2bUser) {
            
        } else {
            $user = B2bUser::model()->findByPk($user);
        }

        $item["uid"] = $user->id;
        $item["username"] = $user->username;
        $item["gender"] = $user->gender;

        $item["realname"] = "";
        if ($user->realname)
            $item["realname"] = $user->realname;

        $item["email"] = "";
        if ($user->email)
            $item["email"] = $user->email;

        $item["telephone"] = $user->telephone;

        $item["identity_no"] = "";
        if ($user->identity_no)
            $item["identity_no"] = $user->identity_no;


        return $item;
        // return JSONHelper::retInfo(true, $item);
    }

    /**
     * 
     */
    public function checkTicket($arr) {
        if (!isset($arr["uid"]) || !isset($arr["appoint"])) {
            //错误，非法请求
            return JSONHelper::ERROR_ILLEGAL_REQUEST; //JSONHelper::echoJSON(false, JSONHelper::ERROR_ILLEGAL_REQUEST);
        }
        $appoint = $arr["appoint"];
        if (!isset($appoint["identity_no"]) || !isset($appoint["realname"]) || !isset($appoint["telephone"])) {
            return JSONHelper::ERROR_ILLEGAL_REQUEST;
        }
        $ticket = null;
        if (isset($arr["tid"]) && $arr["tid"] != null) {
            $ticket = B2bTicket::model()->findByPk($arr["tid"]);
            if (null === $ticket) {
                return JSONHelper::ERROR_NOEXIST_TICKET;
            }
            if ($ticket->uid != $arr["uid"]) {
                return JSONHelper::ERROR_TICKET_BIND;
            }
        } elseif (isset($arr["activecode"]) && !empty($arr["activecode"])) {
            $ticket = B2bTicket::model()->findByAttributes(array("activecode" => $arr["activecode"]));
            if (null === $ticket) {
                return JSONHelper::ERROR_NOEXIST_TICKET;
            }
            if ($ticket->user === null) {
                $ticket->uid = $arr["uid"];
                try {
                    if ($ticket->update() === false) {
                        return JSONHelper::ERROR_SERVICE;
                    }
                } catch (Exception $exc) {
                    return JSONHelper::ERROR_SERVICE;
                }
            } elseif ($ticket->uid != $arr["uid"]) {
                return JSONHelper::ERROR_ACTIVECODE_USED;
            }
        } else {
            $ticket = B2bTicket::model()->findByAttributes(
                    array("identity_no" => $appoint["identity_no"], "realname" => $appoint["realname"],
                "tstatus" => B2bTicket::UNACTIVATED), "companyid<>0");
            if ($ticket === null) {
                return JSONHelper::ERROR_NOEXIST_TICKET;
            }
            if ($ticket->uid == 0) {
                $ticket->uid = $arr["uid"];
                try {
                    if ($ticket->update() === false) {
                        return JSONHelper::ERROR_SERVICE;
                    }
                } catch (Exception $exc) {
                    return JSONHelper::ERROR_SERVICE;
                }
            } elseif ($ticket->uid != $arr["uid"]) {
                return JSONHelper::ERROR_ACTIVECODE_USED;
            }
        }
        if ($ticket === null) {
            return JSONHelper::ERROR_NOEXIST_TICKET;
        }

        if ($ticket->tstatus != B2bTicket::UNACTIVATED&&$ticket->tstatus != B2bTicket::YUYUE_REFUSED) {
            return JSONHelper::ERROR_ILLEGAL_STATUS;
        }
        $item["tid"] = $ticket->id;
        $item["startdate"] = $ticket->startdate;
        $item["enddate"] = $ticket->enddate;
        $item["ticketinfo"] = array();
        if ($ticket->packageid == 0) {
            //查找ticket关联多个package情况
        } elseif ($ticket->package !== null) {
            $package["packageid"] = $ticket->package->id;
            $package["packagename"] = $ticket->package->name;
            $package["centers"] = array();
            if (count($ticket->package->centers) == 0) {
                return JSONHelper::ERROR_PACKAGE_NOTWITHCENTERS;
            }
            foreach ($ticket->package->centers as $c) {
                if ($c->center == null) {
                    continue;
                }
                $center["id"] = $c->center->id;
                $center["name"] = $c->center->name;
                $center["address"] = $c->center->address;
                $center["province"] = $c->center->province;
                $center["city"] = $c->center->city;
                //$c["telephone"] = $ticket->center->telephone;
                $center["gps_lat"] = $c->center->gps_lat;
                $center["gps_lon"] = $c->center->gps_lon;
                array_push($package["centers"], $center);
            }
            array_push($item["ticketinfo"], $package);
        } else {
            return JSONHelper::ERROR_PACKAGE;
        }
        return $item;
    }

    /**
     * 预约提交接口
     * @param appoint[userID]:用户id
     * @param appoint[subCenterID]:子体检中心id
     * @param appoint[date]:预约时间
     * 返回 预约结果字符串
     * @return boolean whether the update is successful
     */
    public function appointment($arr) {
        if (!isset($arr["uid"]) || !isset($arr["appoint"]) || !isset($arr["tid"])) {
            //错误，非法请求

            return JSONHelper::ERROR_ILLEGAL_REQUEST; //JSONHelper::echoJSON(false, JSONHelper::ERROR_ILLEGAL_REQUEST);
        }
        $appoint = $arr["appoint"];
        if (!isset($appoint["subcenterID"]) || !isset($appoint["date"]) || !isset($appoint["identity_no"]) || !isset($appoint["realname"]) || !isset($appoint["telephone"]) || !isset($appoint["packageid"])) {
            return JSONHelper::ERROR_ILLEGAL_REQUEST;
        }

        $userID = trim($arr["uid"]); //intval(trim)
        $tid = trim($arr["tid"]); //intval(trim)
        $subcenterID = trim($appoint["subcenterID"]);


        //从b2b_user表中获取员工信息
        $ticket = B2bTicket::model()->findByAttributes(array(
            "id" => $tid, "uid" => $userID
        ));
        if (null === $ticket) {
            return JSONHelper::ERROR_ILLEGAL_TICKET;
        }
        if ($ticket->tstatus != B2bTicket::UNACTIVATED&&$ticket->tstatus != B2bTicket::YUYUE_REFUSED) {
            return JSONHelper::ERROR_ILLEGAL_STATUS;
        }

        if (intval($ticket->companyid) != 0) {
            $realname = $ticket->realname;
            $identity_no = $ticket->identity_no;
            if (strcmp(trim($realname), trim($appoint["realname"])) || strcmp(trim($identity_no), trim($appoint["identity_no"]))) {
                return JSONHelper::ERROR_TICKET_INFO;
            }
        } else {
            $ticket->identity_no = trim($appoint["identity_no"]);
            $ticket->realname = trim($appoint["realname"]);
        }
        if (intval($ticket->packageid) == 0) {
            //去激活码+套餐表查找是否是关联的套餐
            $ticket->packageid = $appoint["packageid"];
        } elseif ($ticket->packageid != $appoint["packageid"]) {
            return JSONHelper::ERROR_PACKAGE;
        }
        //检验时间格式
        try {
            $date = new DateTime($appoint["date"]);
        } catch (Exception $e) {
            return JSONHelper::ERROR_DATE_FORMAT;
        }
        //检测是否提前1天预约
        $tomorrow = new DateTime('tomorrow');
        if ($date < $tomorrow) {
            return JSONHelper::ERROR_DATE;
        }
        //检测有效期
//        if($ticket->startdate!==$ticket->enddate){
            if (date_create($ticket->startdate . " 00:00:00") > $date || $date > date_create($ticket->enddate . " 00:00:00")) {
                return JSONHelper::ERROR_TICKET_EXPIRE;
            }
//        }


        //查找体检中心信息
        $center = B2bSubCenter::model()->findByPk($subcenterID);
        if ($center === null) {
            return JSONHelper::ERROR_CENTER_EXISTS;
        }



        $ticket->tstatus = B2bTicket::YUYUE_PROCESSING;

        $ticket->telephone = trim($appoint["telephone"]);
        $ticket->centerid = $subcenterID;
        $ticket->examdate = $date->format("Y-m-d");
        try {
            $sms = new SmsService();
            $sms->send("18701375406", "用户:{$ticket->telephone},预约日期:{$appoint['date']}".
                    ",体检中心:{$ticket->center->name}");
            if (false === $ticket->update()) {
                throw new Exception("更新数据失败");
            }
        } catch (Exception $exc) {
            $sms = new SmsService();
            $sms->send("18701375406", "用户:{$ticket->telephone},预约日期:{$appoint['date']}".
                    ",体检中心:{$ticket->center->name},数据库异常而失败");
            return JSONHelper::ERROR_SERVICE;
        }
        return true;
    }

    /**
     * 取消注册
     */
    public function cancelBooking($arr) {
        if (!isset($arr["uid"]) || !isset($arr["tid"])) {
            return JSONHelper::ERROR_ILLEGAL_REQUEST;
        }

        $ticket = B2bTicket::model()->findByAttributes(array(
            "id" => $arr['tid'], "uid" => $arr["uid"]
        ));
        if (null === $ticket) {
            return JSONHelper::ERROR_ILLEGAL_TICKET;
        }
        if ($ticket->package === null || $ticket->package->centers === array()) {
            return JSONHelper::ERROR_SERVICE;
        }
        if ($ticket->tstatus != B2bTicket::YUYUE_PROCESSING) {
            return JSONHelper::ERROR_ILLEGAL_STATUS;
        }

        try {
            $ticket->tstatus = B2bTicket::UNACTIVATED;
            if (intval($ticket->companyid) == 0) {
                $ticket->realname = "";
                $ticket->identity_no = "";
            }
            $ticket->telephone = "";
            $ticket->centerid = 0;
            $ticket->examdate = null;
            if ($ticket->update() === false) {
                throw new Exception("b2bticket update error $ticket->id");
            }
        } catch (Exception $e) {
            return JSONHelper::ERROR_SERVICE;
        }
        return true;
    }

    /*
     * 查询预约结果
     * 参数 $_POST['uid']
     * @return array $myOrder
     */

    public function getMyOrder($arr) {
        if (!isset($arr['uid'])) {
            return JSONHelper::ERROR_ILLEGAL_UID;
        }
        $uid = trim($arr['uid']);
        $rets = B2bOrder::model()->findAllByAttributes(array("customer_id" => $uid), array("order" => "id desc"));

        if ($rets == null) {
            return JSONHelper::ERROR_EMPTY_ORDER;
        }
        $myOrder = array();
        foreach ($rets as $k => $v) {
            $item["id"] = $v->id;
            $item["center_id"] = $v->center_id;             //体检中心id
            $item["sub_center_id"] = $v->sub_center_id;     //子体检中心id
            $item["sub_center_name"] = $v->sub_center_name;     //子体检中心名称
            $item["customer_id"] = $v->customer_id;         //用户id
            $item["customer_name"] = $v->customer_name;     //用户名称
            $item["customer_gender"] = $v->customer_gender; //用户性别
            $item["order_time"] = $v->order_time;           //预约时间
            $item["customer_no"] = $v->customer_no;         //证件号码
            $item["customer_telephone"] = $v->customer_telephone; //用户电话
            $item["email"] = $v->email;                     //用户邮箱
            $item["order_type"] = $v->order_type;           //类型，0企业，1散户
            $item["customer_company"] = $v->customer_company; //用户公司
            //            $item["card_type"] = $v->card_type;
            $item["card_no"] = $v->card_no;
            //            $item["card_type"] = $v->card_type;
            //            $item["order_item_type"] = $v->order_item_type;
            $item["order_item_id"] = $v->order_item_id;
            $item["status"] = $v->status;  //1为新预约，2为预约成功，3为已体检，4为取消
            if ($v->status == B2bOrder::GEREN_CANCEL_MSG) {
                $item["msg"] = $v->etc;
            } else {
                $item["msg"] = "";
            }
            //          $item["exam_id"]=$v->exam_id;
            $item["create_at"] = $v->create_at;
            array_push($myOrder, $item);
        }
        return $myOrder;
    }

    /**
     * 功能：获取体检报告列表
     */
    public function getReportList($arr) {
        if (!isset($arr['uid'])) {
            return JSONHelper::ERROR_ILLEGAL_REQUEST;
        }
        $uid = $arr['uid'];
        $ret = EvaluateReportLog::model()->with(array("ticket"))->findAllByAttributes(
                array("uid" => $uid,'type'=> 
                    array(EvaluateReportLog::TYPE_YJX,  EvaluateReportLog::TYPE_USER)),
                array("order" => "`t`.id desc"));
        $items = array();
        foreach ($ret as $it) {
            $item["id"] = $it->id;
            $item["type"] = $it->type;
            $item["centername"] = "";
            $item["packagename"] = "";
            $item["companyname"] = "";
            if($it->type == EvaluateReportLog::TYPE_USER){
                $ret = EvaluateReportCache::model()->getUserBasicInfo($uid, $it->no);
                $item["realname"] = isset($ret["姓名"])?$ret["姓名"]:"未填写";
                $item["examdate"] = isset($ret["体检日期"])?$ret["体检日期"]:"未填写";
                $item["identity_no"] = isset($ret["身份证"])?$ret["身份证"]:"";
                array_push($items, $item);
                continue;
            }
            if ($it->ticket === null) {
                continue;
            }
            $item["realname"] = $it->ticket->realname;
            $item["examdate"] = $it->ticket->examdate;
            $item["identity_no"] = $it->ticket->identity_no;
            if ($it->ticket->center !== null) {
                $item["centername"] = $it->ticket->center->name;
            }
            if ($it->ticket->package !== null) {
                $item["packagename"] = $it->ticket->package->name;
            }
            if ($it->ticket->company !== null) {
                $item["companyname"] = $it->ticket->company->name;
            }
            
            array_push($items, $item);
        }
        return $items;
    }

    /**
     * 转发体检报告
     */
    public function reportForward($arr) {
        if (!isset($arr["uid"]) || !isset($arr["orderid"]) || !isset($arr["email"])) {
            return JSONHelper::ERROR_ILLEGAL_REQUEST;
        }
        $ret = B2bOrder::model()->findByPk($arr["orderid"]);
        if (null === $ret) {
            return JSONHelper::ERROR_NOEXIST_ORDER;
        }
        if ($ret->customer_id != $arr["uid"]) {
            return JSONHelper::ERROR_ILLEGAL_ORDER;
        }
        $file = Yii::app()->basePath . "/../pdf/000101611121000074.pdf";
        if ($ret->status != B2bOrder::TJ_REPORT || !file_exists($file)) {
            return JSONHelper::ERROR_NOEXIST_REPORT;
        }
        try {
            Yii::import('application.extensions.phpmailer.JPhpMailer');
            $mail = new JPhpMailer;
            $mail->IsSMTP();
            $mail->Host = 'smtp.qq.com';
            $mail->SMTPAuth = true;
            $mail->Username = 'support@pocdoc.cn';
            $mail->Password = 'Pocdoc@1310';
            $mail->SetFrom('support@pocdoc.cn', '郁金香体检联盟');
            $mail->Subject = '郁金香体检联盟';
            $con = '用户' . $ret->customer_name . "您好，请查收您的体检报告";
            //$mail->AltBody = 
            $mail->MsgHTML($con);
            $mail->AddAttachment($file, "体检报告.pdf", "binary");
            //$mail->SetLanguage("ch");
            $mail->AddAddress($arr['email'], $ret->customer_name);
            if (false === $mail->Send()) {
                ob_clean();
                return JSONHelper::ERROR_FAILURE_EMAIL;
            }
            return true;
        } catch (Exception $e) {
            return JSONHelper::ERROR_EXCEPT_EMAIL;
        }
    }

    /*
     * 功能：输出制定地点周围的体检中心
     * 参数：uid-用户id，lat-当前的维度, lon-当前的经度，radius-查找范围(单位是米)
     * 返回：范围内体检中心信息列表的json串
     * @return array $response
     */

    public function centerSearch($arr) {
        if (isset($arr['uid'])) {
            $uid = $arr['uid'];

            //从b2b_user表中获取员工信息
            $rets_B2bUser = B2bUser::model()->findByPk($uid);
            if ($rets_B2bUser === null) {
                return JSONHelper::ERROR_USER_EXISTS;
            }
            $rets = B2bExternalUser::model()->getLastExamination($rets_B2bUser->identity_no);
            if ($rets === NULL) {
                return JSONHelper::ERROR_RECORDS_EXISTS;
            }

            $centers = array();
            foreach ($rets->centers as $it) {
                array_push($centers, $it->sub_center_id);
            }

            $gps_lat = isset($arr['gps_lat']) ? $arr['gps_lat'] : Constants::DEFAULT_SEARCH_LAT;
            $gps_lon = isset($arr['gps_lon']) ? $arr['gps_lon'] : Constants::DEFAULT_SEARCH_LON;
            $radius = isset($arr['radius']) ? $arr['radius'] : Constants::DEFAULT_SEARCH_RADIUS;
            $cn = isset($arr['cn']) ? $arr['cn'] : "";
            $response["centers"] = array();
            $response["gps_lat"] = $gps_lat;
            $response["gps_lon"] = $gps_lon;
            try {
                $model = B2bSubCenter::model();
                $data = $model->centerSearch($gps_lat, $gps_lon, $radius, $cn, $centers);
                foreach ($data as $it) {
                    $item["centerID"] = $it->id;
                    //                    $item["center_id"] = $it->center_id;
                    $item["name"] = $it->name;
                    $item["province"] = $it->province;
                    $item["city"] = $it->city;
                    $item["address"] = $it->address;
                    $item["telephone"] = $it->telephone;
                    $item["gps_lat"] = $it->gps_lat;
                    $item["gps_lon"] = $it->gps_lon;
                    array_push($response["centers"], $item);
                }
            } catch (Exception $e) {
                return JSONHelper::ERROR_CENTER_SEARCH;
            }
        } else {
            return JSONHelper::ERROR_ILLEGAL_UID;
        }
        return $response;
    }

    /*
     * 找回密码功能
     * @param username  用户名
     */

    public function getPassword($arr) {
        if (!isset($arr["email"])) {
            return JSONHelper::ERROR_ILLEGAL_REQUEST;
        }
        $user = B2bUser::model()->findByAttributes(array("email" => $arr["email"]));
        if ($user === null) {
            return JSONHelper::ERROR_EMPTY_EMAIL;
        }
        $newpw = $this->generate_password();
        try {
            Yii::import('application.extensions.phpmailer.JPhpMailer');
            $mail = new JPhpMailer;
            $mail->IsSMTP();
            $mail->Host = 'smtp.qq.com';
            $mail->SMTPAuth = true;
            $mail->Username = 'support@pocdoc.cn';
            $mail->Password = 'Pocdoc@1310';
            $mail->SetFrom('support@pocdoc.cn', '郁金香体检联盟');
            $mail->Subject = '郁金香体检联盟密码重置';
            $con = '用户' . $user->username . "您好，你的新密码为：" . $newpw;
            //$mail->AltBody = 
            $mail->MsgHTML($con);
            //$mail->SetLanguage("ch");
            $mail->AddAddress($arr['email'], $user->username);
            if (false === $mail->Send()) {
                ob_clean();
                return JSONHelper::ERROR_FAILURE_EMAIL;
            }
            $user->password = md5($newpw);
            $user->update();
            return true;
        } catch (Exception $e) {
            return JSONHelper::ERROR_EXCEPT_EMAIL;
        }
    }

    function generate_password($length = 6) {
// 密码字符集，可任意添加你需要的字符
        $chars = 'abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ123456789';
        $password = '';
        for ($i = 0; $i < $length; $i++) {
// 这里提供两种字符获取方式
// 第一种是使用 substr 截取$chars中的任意一位字符；
// 第二种是取字符数组 $chars 的任意元素
// $password .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
            $password .= $chars[mt_rand(0, strlen($chars) - 1)];
        }
        return $password;
    }
    /*
     * 删除体检报告
     */
    function ReportDel($arr)
    {
        if (!isset($arr['uid'])||!isset($arr["reportid"])) {
            return JSONHelper::ERROR_ILLEGAL_REQUEST;
        }
        $ret = EvaluateReportLog::model()->findByAttributes(
                array("id" => $arr['reportid'], "uid" =>$arr["uid"],
                    "type"=>  EvaluateReportLog::TYPE_USER)
               );
        if ($ret === null) {
            return JSONHelper::ERROR_NOEXIST_REPORT;
        }
        EvaluateReportCache::model()->deleteAll("uid={$arr['uid']} and no='$ret->no'");
        if(false===$ret->delete()){
            return JSONHelper::ERROR_SERVICE;
        }
        return TRUE;
    }

    /**
     * 返回个人资料及异常信息
     * 
     * @param type $arr
     * @return type
     */
    function getUserIssue($arr) {
        if (!isset($arr['uid'])) {
            return JSONHelper::ERROR_ILLEGAL_REQUEST;
        }
        $result = array();
        $ret = B2bOrder::model()->findByAttributes(array("customer_id" => $arr['uid'], "status" => 5), array("order" => "order_time desc"));
        if ($ret === null) {
            return JSONHelper::ERROR_NOTEXIST_ORDER;
        } else {
            $result['company_name'] = $ret->customer_company;
            $result['customer_name'] = $ret->customer_name;
            $result['customer_gender'] = $ret->customer_gender;
            $result['customer_no'] = $ret->customer_no;
            $result['order_time'] = $ret->order_time;
            $result['sub_center_name'] = $ret->sub_center_name;
            $result['order_type'] = $ret->order_type;
            if ($ret->package !== null) {
                $result['package'] = ($ret->package !== null) ? $ret->package->name : '';
            }
            if ($ret->telphone !== null) {
                $result['telphone'] = ($ret->telphone !== null) ? $ret->telphone->telephone : '';
            }
        }

        $criteria = new CDbCriteria;
        $criteria->select = 'json_data,no';
        $criteria->condition = 'uid=:uid';
        $criteria->params = array(':uid' => $arr['uid']);
        $criteria->order = 'id DESC';
        $criteria->limit = 1;
        $data = EvaluateReportIssueJsonCache::model()->find($criteria);
        if ($data === null) {
            return JSONHelper::ERROR_NOTEXIST_REPORT;
        } else {
            $result['info'] = json_decode($data->json_data);
        }
        return $result;
    }

    /**
     * 获取体检报告url
     * 
     */
    function getReportWithSmsCaptcha($arr) {
        if (!isset($arr["captcha"]) || !isset($arr["telephone"]) || !isset($arr["identity_no"]) || !isset($arr["realname"])) {
            return JSONHelper::ERROR_ILLEGAL_REQUEST;
        }
        if ($this->verifySmsCaptcha($arr["telephone"], $arr["captcha"]) === false) {
            return JSONHelper::ERROR_SMS_VERIFY;
        }
        $ticket = B2bTicket::model()->findByAttributes(array("identity_no" => $arr["identity_no"],
            "realname" => $arr["realname"], "tstatus" => 4), array("order" => "id desc"));
        if ($ticket === null) {
            return JSONHelper::ERROR_NOTEXIST_REPORT;
        }
        if ($ticket->telephone != $arr["telephone"]) {
            return JSONHelper::ERROR_ILLEGAL_TICKET;
        }
        return true;
    }

    /**
     * 获取体检报告数据
     * 
     * @param type $arr
     * @return type $arr or JSONHelper::ERROR_ILLEGAL_REQUEST  JSONHelper::ERROR_NOEXIST_REPORT
     */
    function getReportInfo($arr) {
        if (isset($arr["captcha"]) && isset($arr["telephone"]) && isset($arr["identity_no"]) && isset($arr["realname"])) {
            if ($this->verifySmsCaptcha($arr["telephone"], $arr["captcha"]) === false) {
                return JSONHelper::ERROR_SMS_VERIFY;
            }
            $ticket = B2bTicket::model()->findByAttributes(array("identity_no" => $arr["identity_no"],
                "realname" => $arr["realname"], "tstatus" => 4), array("order" => "id desc"));
            if ($ticket === null) {
                return JSONHelper::ERROR_NOTEXIST_REPORT;
            }
            if ($ticket->telephone != $arr["telephone"]) {
                return JSONHelper::ERROR_ILLEGAL_TICKET;
            }
            $ret = EvaluateReportLog::model()->findByAttributes(array("tid" => $ticket->id));
        } else {
            if (!(isset($arr['uid']) && isset($arr['reportid']))) {//缺少参数
                return JSONHelper::ERROR_ILLEGAL_REQUEST;
            }
            $ret = EvaluateReportLog::model()->findByAttributes(array("id" => $arr["reportid"], "uid" => $arr["uid"]));
        }

        if ($ret === null) {
            return JSONHelper::ERROR_ILLEGAL_TICKET;
        }

//        $ret = EvaluateReportJsonCache::model()->findByAttributes(array('uid'=>$arr['uid'],'no'=>$ret->no),array("order"=>"id desc"),array('limit'=>1));
        $ret = EvaluateReportCache::model()->with("indicator")->findAllByAttributes(array(
            "no" => $ret->no
        ));
        if (count($ret) == 0) {//导入的体检数据不存在
            return JSONHelper::ERROR_NOEXIST_REPORT;
        } else {//查询成功
            return $ret;
        }
    }

    /**
     * 获取体检报告数据
     * 
     * @param type $arr
     * @return type $arr or JSONHelper::ERROR_ILLEGAL_REQUEST  JSONHelper::ERROR_NOEXIST_REPORT
     */
    function getReportArrayInfo($arr) {
        if (!(isset($arr['uid']) && isset($arr['orderid']))) {//缺少参数
            return JSONHelper::ERROR_ILLEGAL_REQUEST;
        }
        $order = B2bOrder::model()->findByAttributes(array("id" => $arr['orderid'], "status" => 5));
        if ($order === null) {//订单不存在
            return JSONHelper::ERROR_NOEXIST_ORDER;
        }
        $basic = EvaluateReportCache::model()->findAllByAttributes(array("uid" => $arr['uid'], "no" => $order->exam_id, "parent_name" => "basic"));
        if ($basic === null) {
            return JSONHelper::ERROR_NOEXIST_REPORT;
        }
        $info = EvaluateReportCache::model()->findAllByAttributes(array("uid" => $arr['uid'], "no" => $order->exam_id));
        if ($info === null) {
            return JSONHelper::ERROR_NOEXIST_REPORT;
        }
        return array("basic" => $basic, "info" => $info);
    }

    function setUserDevice($arr) {
        if (!(isset($arr['uid']) && isset($arr['did']))) {//缺少参数
            return JSONHelper::ERROR_ILLEGAL_REQUEST;
        }
        $uid = intval($arr['uid']);
        $did = $arr['did'];
        //1.通过did查找数据
        $bind = B2bPushAndroidBindUser::model()->findByAttributes(array('device_token' => $did));
        if ($bind === null) {//插入数据
            $temps = new B2bPushAndroidBindUser;
            $temps->uid = $uid;
            $temps->device_token = $did;
            $temps->save(false);
        } else if ($bind->uid != $uid) {
            $bind->uid = $uid;
            $bind->save(false);
        } else {
            return 0;
        }
        return 1;
    }
    /**
     * 下订单,生成一条记录，代付款
     */
    public function setPurchaseRecords($arr)
    {
        if(!isset($arr["uid"])||!isset($arr["packageid"])
                ||!isset($arr["num"])||!isset($arr["totalprice"])){
            return JSONHelper::ERROR_ILLEGAL_REQUEST;
        }
        $package = B2bPackage::model()->findByAttributes(array(
                    "id"=>$arr["packageid"],"type"=>  B2bPackage::PUBLIC_USER
                ));
        if($package === null){
            return JSONHelper::ERROR_PACKAGE;
        }
        if($package->sale_price/100 * $arr["num"] != $arr["totalprice"]){
            return JSONHelper::ERROR_PACKAGE_PRICE;
        }
        
        $record = new B2cPurchaseRecords();
        $record->uid = $arr["uid"];
        $record->unitprice = $package->sale_price;
        $record->num = $arr["num"];
        $record->totalprice = $package->sale_price * $arr["num"];
        $record->packageid = $arr["packageid"];
        $record->status = B2cPurchaseRecords::WAITING_PAY;
        $record->create_at = new CDbExpression("NOW()");
        $trans = Yii::app()->db->beginTransaction();
        try{
            if(false === $record->save()){
                throw new Exception("数据保存失败");
            }
            $sn = sprintf("%06d",$record->id);
            $record->serialnumber = date("YmdHis").$sn;
            if(false === $record->update()){
                throw new Exception("记录序列号生成失败");
            }
            $trans->commit();
        } catch (Exception $ex) {
            $trans->rollback();
            
            return JSONHelper::ERROR_SERVICE;
        }
        $item["id"] = $record->id;
        $item["name"] = $package->name;
        $item["descption"] = $package->name."*".$record->num;
        $item["sn"] = $record->serialnumber;
        $item["unitprice"] = $record->unitprice/100;
        $item["num"] = $record->num;
        $item["totalprice"] = $record->totalprice/100;
        return $item;
    }
    /**
     * 用户付款成功，生成Ticket
     */
    public function genTicketByAliidAndSn($aliid,$sn)
    {
        $item = B2cPurchaseRecords::model()->findByAttributes(array(
                     "serialnumber"=>$sn
                ));
        if($item === null){
            return false;
        }
        if($item->status == B2cPurchaseRecords::FINISH_PAY){
            return true;
        }
        $ret["items"] = array();
        $trans = Yii::app()->db->beginTransaction();
        try {
            $item->aliid = $aliid;
            
            for($i = 0;$i<$item->num;$i++){
                $ticket = new B2bTicket();
                $ticket->uid = $item->uid;
                $ticket->packageid = $item->packageid;
                $ticket->tstatus = B2bTicket::UNACTIVATED;
                if($item->package!==null){
                    $ticket->startdate = $item->package->startdate;
                    $ticket->enddate = $item->package->enddate;
                }
                
                if(false === $ticket->save()){
                    throw new Exception("TICKET数据保存错误");
                }
                $ticket->activecode = B2bTicket::encActiveCode($ticket->id);
                if(false === $ticket->update()){
                    throw new Exception("TICKET ActiveCode保存错误");
                }
                $t["id"] = $ticket->id;
                $t["uid"] = $ticket->uid;
                $t["packageid"] = $ticket->packageid;
                $t["activecode"] = $ticket->activecode;
                array_push($ret["items"],$t);
                
                $item->activecodes .= $ticket->activecode.";";
            }
            $item->status = B2cPurchaseRecords::FINISH_PAY;
            if(false === $item->update()){
                throw new Exception("aliid Ticket保存错误");
            }
            $trans->commit();
            $ret["aliid"] = $item->aliid;
            $ret["sn"] = $item->serialnumber;
            $ret["uid"] = $item->uid;
        } catch (Exception $exc) {
            $trans->rollback();
            return false;
        }
        return $ret;
    }
    /**
     * 
     * @param 获取消息列表
     */
    public function getMsgList($arr){
        if(!isset($arr["uid"])){
            return JSONHelper::ERROR_ILLEGAL_REQUEST;
        }
        $minid = isset($arr["minid"])?$arr["minid"]:0;
        $page = isset($arr["page"])?$arr["page"]:1;
        try{
            $ret = B2cMsgRecords::model()->findAll(
                array("condition"=>"uid=:uid and id>:id","offset"=>($page-1)*20,"limit"=>20,
                    "order"=>"id desc",
                    "params"=>array(":uid"=>$arr["uid"],":id"=>$minid)));
        } catch (Exception $ex) {
            return JSONHelper::ERROR_SERVICE;
        }
        $items = array();
        foreach($ret as $it){
            $item["id"] = $it->id;
            $item["title"] = $it->title;
            $item["type"] = $it->type;
            $item["description"] = $it->description;
            $item["date"] = $it->create_at;
            array_push($items, $item);
        }
        return $items;
    }

    /**
     * 发送验证短信
     */
    function getSmsCaptcha($arr, $expire = 600) {
        if (!isset($arr["telephone"])||!isset($arr["action"])) {
            return JSONHelper::ERROR_ILLEGAL_REQUEST;
        }
        $action = strtolower(trim($arr["action"]));
        switch ($action) {
            case "signup":
                $ret = B2bUser::model()->findByAttributes(array(
                        "username"=>$arr["telephone"]
                    ));
                if($ret !== null){
                    return JSONHelper::ERROR_USER_EXISTS;
                }
                break;
            case "pwdreset":
                $ret = B2bUser::model()->findByAttributes(array(
                        "username"=>$arr["telephone"]
                    ));
                if($ret === null){
                    return JSONHelper::ERROR_NOEXIST_USER;
                }
                break;
            case "getreport":
                break;
            default:
                return JSONHelper::ERROR_ILLEGAL_REQUEST;
                break;
        }
        
        
        $sms = new SmsService();
        $now = time();
        $ret = Yii::app()->cache->get("sms_" . $arr["telephone"]);
        if ($ret === false) {
            $num = mt_rand(0, 9999);
            $num = sprintf("%04d", $num);
            $item["captcha"] = $num;
            $item["count"] = 1;
        } else {
            $item = (array) json_decode($ret);
            if (($now - $item["time"]) < 60||$item["count"]>5) {
                return JSONHelper::ERROR_SMS_FRUQUENCY;
            }
            $item["count"] ++;
        }
        $item["time"] = $now;
        $cache = json_encode($item);
        try {
            Yii::app()->cache->set("sms_" . $arr["telephone"], $cache, $expire);
        } catch (Exception $exc) {
            return JSONHelper::ERROR_SERVICE;
        }

        $msg = "您好，您的验证码是:" . $item["captcha"] . "，十分钟内有效，请勿将验证码泄露给其他人。【掌上体检专业版】";

        $ret = $sms->send($arr["telephone"], $msg);
        if ($ret === false) {
            return JSONHelper::ERROR_SMS_SERVICE;
        }

        return true;
    }

    private function verifySmsCaptcha($telephone, $captcha) {
        $ret = Yii::app()->cache->get("sms_" . $telephone);
        if ($ret === false) {
            return false;
        }
        $item = (array) json_decode($ret);
        if ($item["captcha"] != $captcha) {
            return false;
        }
        $cache = json_encode($item);
        try {
            Yii::app()->cache->set("sms_" . $telephone, $cache, 600);
        } catch (Exception $exc) {
            return false;
        }
        return true;
    }

}
